package com.gxy.learn.backup.shiroauth.shiro.config;

import com.gxy.learn.backup.shiroauth.service.SysMenuService;
import com.gxy.learn.backup.shiroauth.service.SysRoleService;
import com.gxy.learn.backup.shiroauth.service.SysUserService;
import com.gxy.learn.backup.shiroauth.shiro.filter.JwtAuthFilter;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.servlet.Filter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Description(Shiro配置)
 * @author: Gao xueyong
 * Create at: 2022/2/12 下午11:51
 */
@Configuration
public class ShiroConfig {


    @Autowired
    private CacheManager cacheManager;

    /**
     * 先经过token过滤器，如果检测到请求头存在 token，则用 token 去 login，接着走 Realm 去验证
     */
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager, JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary,
                                          SysUserService sysUserService , SysMenuService sysMenuService) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        Map<String, Filter> filterMap = new LinkedHashMap<>();
        //设置我们自定义的JWT过滤器
        filterMap.put("jwtAuthFilter", new JwtAuthFilter(jwtVerifyTokenAuxiliary,sysUserService,sysMenuService));
        factoryBean.setFilters(filterMap);

        factoryBean.setSecurityManager(securityManager);
        factoryBean.setUnauthorizedUrl("/unauthorized/无权限");
        Map<String, String> filterRuleMap = new HashMap<>();
        // 所有请求通过我们自己的JWT Filter
        filterRuleMap.put("/**", "jwtAuthFilter");


        //内置过滤器，可以实现权限相关的拦截器
        //  user：如果使用remember的功能才能直接访问
        //  perms：必须得到资源权限才可访问
        //  role：必须得到角色权限才可访问

        // 放行不需要权限认证的接口
        // swagger 静态资源 或websocket服务器链接接口 都可在此配置
        filterRuleMap.put("/login", "anon");
        filterRuleMap.put("/logout", "noSessionCreation,jwtAuthFilter");
        filterRuleMap.put("/unauthorized/**", "anon");

//        跳过拦截
//        filterRuleMap.put("/v2/**", "noSessionCreation,anon");
        factoryBean.setFilterChainDefinitionMap(filterRuleMap);
        return factoryBean;

    }

    @Bean(name = "shiroRealm")
    @DependsOn("lifecycleBeanPostProcessor")
    public ShiroRealm shiroRealm(SysUserService sysUserService,
                                 SysRoleService sysRoleService,
                                 SysMenuService sysMenuService) {
        ShiroRealm shiroRealm = new ShiroRealm(sysUserService, sysRoleService, sysMenuService);
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setCacheManager(cacheManager);
        return shiroRealm;
    }

    @Bean(name = "jwtShiroRealm")
    @DependsOn("lifecycleBeanPostProcessor")
    public JwtShiroRealm jwtShiroRealm(SysUserService sysUserService,
                                       SysRoleService sysRoleService,
                                       SysMenuService sysMenuService, JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary) {
        JwtShiroRealm shiroRealm = new JwtShiroRealm(sysUserService, sysRoleService, sysMenuService, jwtVerifyTokenAuxiliary);
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setCacheManager(cacheManager);
        return shiroRealm;
    }


    /**
     * 注入 securityManager
     */
    @Bean
    public DefaultWebSecurityManager securityManager(SysUserService sysUserService, SysRoleService sysRoleService, SysMenuService sysMenuService, JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealms(Arrays.asList(new ShiroRealm(sysUserService, sysRoleService, sysMenuService), new JwtShiroRealm(sysUserService, sysRoleService, sysMenuService, jwtVerifyTokenAuxiliary)));
        securityManager.setCacheManager(cacheManager);
        securityManager.setAuthenticator(authenticator(sysUserService,sysRoleService,sysMenuService,jwtVerifyTokenAuxiliary));

        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }

    @Bean
    public ModularRealmAuthenticator authenticator(SysUserService sysUserService,
                                                   SysRoleService sysRoleService,
                                                   SysMenuService sysMenuService, JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary) {
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
        authenticator.setRealms(Arrays.asList(new ShiroRealm(sysUserService, sysRoleService, sysMenuService), new JwtShiroRealm(sysUserService, sysRoleService, sysMenuService, jwtVerifyTokenAuxiliary)));
//        authenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
        //最新的realm执行成功才算成功
//        authenticator.setAuthenticationStrategy(new AllSuccessfulStrategy());
        authenticator.setAuthenticationStrategy(new MyAtLeastOneSuccessfulStrategy());
        return authenticator;
    }
    /**
     * 添加注解支持
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        // 强制使用cglib，防止重复代理和可能引起代理出错的问题
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SysUserService sysUserService,
                                                                                   SysRoleService sysRoleService,
                                                                                   SysMenuService sysMenuService,
                                                                                   JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager(sysUserService, sysRoleService, sysMenuService, jwtVerifyTokenAuxiliary));
        return advisor;
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}
